<!--
 * @description  : 市管-日计划制定-任务池任务地图查询
 * @descriptionDetail: 市管-日计划制定-任务池任务地图查询
 * @copyright    : 浙江烟草
 * @author       : sy
 * @create       : 2022-09-02 14:57:44
-->
<template>
  <view>
    <!-- #ifdef H5-ONLY -->
    <theme-navbar
      :is-white="false"
      :title="navTitle"
      :custom-back="goBack"
      style="z-index: 99999"
    >
      <view class="nav-right-icon">
        <view @tap="handlerSure">
          确定
        </view>
      </view>
    </theme-navbar>
    <!-- #endif -->
		<!-- #ifdef H5-WECHAT || H5-EMP -->
		<fab-button :content="fContent" @fabtrigger="fabtrigger" />
		<!-- #endif -->
    <view :msg="msg" :style="{'width':'100%','height':getMapHeight()}" :change:msg="amapRender.receiveMsg" id="taskPoolMapContainer"></view>
    <view class="choose-info">
      已选中<span>{{ selectedItems.length }}</span>户
    </view>
    <scroll-view scroll-y="true" :style="{'height':getMapHeight()}">
      <u-swipe-action
        :index="index"
        :show="item.show"
        :options="options"
        :disabled="isDisabled"
        style="border-bottom: 1px solid #e5e5e5;padding: 10px 8px;"
        v-for="(item, index) in selectedItems"
        :key="item.retailerUuid"
        @click="handlerDeleteClient(item)"
        @open="handlerOpen(index)"
      >
        <client-item :client="item"></client-item>
      </u-swipe-action>
    </scroll-view>
  </view>
</template>

<script>
	import checkService from '@/service/check/check.service';
	import ClientItem from './components/client-item.vue';
	import fabButton from '@/components/uni-fab.vue';

	export default {
		components: {
			ClientItem,
			fabButton
		},
		data() {
			return {
				tasks: [], // 任务池数据
				selectedUids: [], // 选中项的ids
				selectedItems: [], // 选中项
				searchData: {
					// 查询参数
					// groupUuid: "",
					// taskMonth: "",
				},
				isDisabled: false,
				options: [{
					text: '删除',
					style: {
						backgroundColor: '#dd524d',
					},
				}, ],
				maped: false, // map 初始化完成的flag
				msg: {
					type: '', //
					obj: {},
				},
				fContent: [{
					iconPath: require('@/static/confirm.png'),
					selectedIconPath: require('@/static/confirm.png'),
					text: '确定',
					active: false,
				}],
			};
		},
		onLoad(opt) {
			// this.searchData.taskType = opt.taskType;
			// this.searchData.checkDate = opt.checkDate;
		},
		mounted() {
			this.setRightBtns();
		},
		methods: {
			getMapHeight() {
				console.log('系统信息', uni.getSystemInfoSync());
				let h = (uni.getSystemInfoSync().windowHeight - 44 - 38) / 2 + 'px';
				// #ifdef H5-DINGDING
				// h = uni.getSystemInfoSync().windowHeight / 2 + 'px'
				// #endif
				return h;
			},
			setRightBtns() {
				// 设置右侧标题
				// #ifdef H5-DINGDING
				this.$deviceApi.setRight('确定', () => {
					this.handlerSure();
					this.setRightBtns();
				}, true, true);
				// #endif
			},
			fabtrigger(btn) {
				if (btn.index == 0) {
					this.handlerSure();
				}
			},
			mapInit() {
				this.maped = true;
			},
			// 删除选中的客户
			handlerDeleteClient(cItem) {
				this.selectedItems = this.selectedItems.filter((c) => c.retailerUuid != cItem.retailerUuid);
				this.selectedUids = [];
				this.selectedItems.forEach((it) => this.selectedUids.push(it.retailerUuid));
				this.msg = {
					type: 'renderSelectedRetailes',
					obj: {
						items: this.selectedItems,
						delItem: cItem,
					},
				};
				this.searchMapTasks();
			},
			handlerOpen(idx) {
				this.selectedItems.map((c, i) => {
					c.show = i == idx;
				});
				this.$forceUpdate();
			},
			// 选中
			handlerSelectItem(items) {
				console.log('选中的零售户', items);
				this.selectedItems = items;
				this.selectedUids = [];
				this.selectedItems.forEach((it) => this.selectedUids.push(it.retailerUuid));
			},
			// 确定
			handlerSure() {
				if (this.selectedItems.length == 0) {
					this.$modal.alert('请选择任务池任务');
					return;
				}
				this.backPrev({
					paramKey: 'keySupervisionTaskMap',
					param: this.selectedItems,
				});
				this.selectedUids = this.selectedItems = [];
			},
		},
	};
</script>
<script module="amapRender" lang="renderjs">
	import checkService from "@/service/check/check.service"
	import {
		AMapMixin,
	} from '@/common/AMapMixin.js';
	import {
		SET_MAP_LAT_LON
	} from '@/config/setting.config.js';

	export default {
		mixins: [AMapMixin, ],
		data() {
			return {
				tasks: [],
				searchData: {}, // 查询参数
				selectedRetailers: [], // 选中的零售户
				markers: [], // 点标记
				retailerIcon: new AMap.Icon({
					size: new AMap.Size(24, 24), // 图标尺寸
					image: require("../../static/check/marker.png"), // Icon的图像
					imageSize: new AMap.Size(24, 24), //,
				}),
				retailerSelectedIcon: new AMap.Icon({
					size: new AMap.Size(24, 24), // 图标尺寸
					image: require("../../static/check/marker_selected.png"), // Icon的图像
					imageSize: new AMap.Size(24, 24), //,
				}),
			}
		},
		onLoad(opt) {
			// this.searchData.taskType = opt.taskType;
			// this.searchData.checkDate = opt.checkDate;
			// TODO this.searchData.taskSource = opt.taskSource;
		},
		methods: {
			initAmap() {
				if (this.$deviceApi.geolocation) {
					this.$deviceApi.geolocation().then(geo => {
						this.curPos = [geo.longitude, geo.latitude, ];
						this.setMapInstance(this.curPos);
					});
				} else {
					this.curPos = SET_MAP_LAT_LON;
					this.setMapInstance(this.curPos);
				}

				let self = this;
				// #ifdef H5-DINGDING || H5-WECHAT
				this.getCurrentLocation().then(
					(res) => {
					  self.curPos = [res.lng, res.lat];
					  self.setMapInstance([res.lng, res.lat]);
					},
					(err) => {
						console.log("getCurrentLocation(err):",JSON.stringify(err))
					}
				);
				// #endif
			},
			setMapInstance(cords) {
				if (!this.hasInited) return;
				let self = this;
				self.curCords = new AMap.LngLat(cords[0], cords[1]);
				self.amap = new AMap.Map('taskPoolMapContainer', {
					center: self.curCords,
					showControlButton: true,
					zoom: 13,
				});
				AMap.plugin([
					'AMap.ToolBar',
					'AMap.Scale',
					'AMap.OverView',
					'AMap.MapType',
					'AMap.Geolocation',
				], () => {
					// 在图面添加工具条控件，工具条控件集成了缩放、平移、定位等功能按钮在内的组合控件
					self.amap.addControl(new AMap.ToolBar());
					// 在图面添加比例尺控件，展示地图在当前层级和纬度下的比例尺
					self.amap.addControl(new AMap.Scale());
					// 在图面添加定位控件，用来获取和展示用户主机所在的经纬度位置
					self.amap.addControl(new AMap.Geolocation());
				});
				self.$ownerInstance.callMethod('mapInit', {});
				self.searchMapTasks();
				// 地图缩放
				self.amap.on("zoomend", function() {
					if (self.markers.length > 0) {
						self.amap.remove(self.markers);
					}
					self.searchMapTasks();
				});
				// 地图移动
				self.amap.on("moveend", function() {
					if (self.markers.length > 0) {
						self.amap.remove(self.markers);
					}
					self.searchMapTasks();
				});
			},
			// 获取可视范围的坐标
			getBoundsData() {
				let tampBounds = this.amap.getBounds();
				let northwest = tampBounds.getNorthWest(); // 西北
				let eastsouth = tampBounds.getSouthEast(); // 东南
				this.searchData.latitudeStart = northwest.lat > eastsouth.lat ? eastsouth.lat : northwest.lat;
				this.searchData.latitudeEnd = northwest.lat > eastsouth.lat ? northwest.lat : eastsouth.lat;
				this.searchData.longitudeStart = northwest.lng > eastsouth.lng ? eastsouth.lng : northwest.lng;
				this.searchData.longitudeEnd = northwest.lng > eastsouth.lng ? northwest.lng : eastsouth.lng;
			},
			// 查询任务池数据
			searchMapTasks() {
				this.$u.loading("数据加载中...");
				this.getBoundsData();
				this.searchData.orgUuid = this.curUser.cityOrgUuid;
				this.searchData.taskStatus = '01'; // 未分配
				this.searchData.taskType = '01';
				this.searchData.taskSubject = ""; // 表示 查询全部 无证户和零售户
				checkService.findPlnInTaskPoolListMap(this.searchData).then(dr => {
					this.$u.hideLoading();
					if (dr.success) {
						if (dr.data.length > 0) {
							dr.data.forEach(retailer => {
								if (!retailer.longitude || !retailer.latitude)
									return;
								let markerConfig = {
									size: new AMap.Size(24, 24), // 图标尺寸
									position: new AMap.LngLat(retailer.longitude, retailer.latitude),
									title: retailer.companyName,
								};
								let marker = new AMap.Marker(markerConfig);
								marker.retailerUuid = retailer.retailerUuid;
								marker.setIcon(this.retailerIcon);
								for (let i = 0; i < this.selectedRetailers.length; i++) {
									if (marker.retailerUuid == this.selectedRetailers[i].retailerUuid) {
										marker.setIcon(this.retailerSelectedIcon);
										this.markers.push(marker);
									}
								}
								marker.on("click", () => {
									// 区分处理标记点击
									if (this.selectedRetailers.filter(it => it.retailerUuid == retailer.retailerUuid).length > 0) {
										this.selectedRetailers = this.selectedRetailers.filter(it => it.retailerUuid != retailer.retailerUuid);
										marker.setIcon(this.retailerIcon);
									} else {
										this.selectedRetailers.push(retailer);
										marker.setIcon(this.retailerSelectedIcon);
									}
									this.$ownerInstance.callMethod('handlerSelectItem', this.selectedRetailers);
								});
								this.markers.push(marker);
								this.amap.add(marker);
							});
						} else {
							// this.amap.remove(this.markers);
						}
					} else {
						this.$u.toast(dr.msg);
					}
				}).catch((err) => {
					this.$u.hideLoading();
					this.$u.toast(err);
				});
			},

			receiveMsg(newVal, oldVal, ownerVm, vm) {
				if (newVal.type == "setMapInstance") {
					this.setMapInstance([newVal.obj.longitude, newVal.obj.latitude, ]);
				} else if (newVal.type == "renderSelectedRetailes") {
					this.selectedRetailers = newVal.obj.items;
					let mk = this.markers.filter(m => m.retailerUuid == newVal.obj.delItem.retailerUuid)[0];
					mk.setIcon(this.retailerIcon);
				}
			},
		},
	}
</script>

<style lang="scss" scoped>
	.sticky-header {
		background-color: #fff;
		position: fixed;
		/* #ifdef H5-DINGDING  */
		top: 0px;
		/* #endif */
		/* #ifndef H5-DINGDING  */
		top: 44px;
		/* #endif */
		width: 100%;
		height: 40px;
		z-index: 999;
		padding: $cm-search-padding-row $cm-search-padding-column;
		height: 55px;
		line-height: 30px;
	}

	.choose-info {
		height: 38px;
		line-height: 38px;
		padding-left: 10px;
		font-size: 16px;
		background-color: #f1f1f1;

		span {
			font-weight: 600;
			margin: 0px 5px;
		}
	}
</style>
